package com.xaut.controller;

import com.xaut.bean.User;
import org.springframework.http.HttpRequest;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;

@Controller
@RequestMapping("/user")
public class UserController {

    @RequestMapping("/index")
    public String index(){
        return "user";
    }


    @RequestMapping("/adduser")
    //接收自定义数据
    public String addUser(User user){
        System.out.println("用户信息："+user);
        //return "success";
        //添加用户成功，跳转到用户列表
        //redirect进行页面重定向
        return "forward:/user/userlist";
    }



    @RequestMapping("/userlist")
    //集合类型数据的传递
    public ModelAndView userList() {


        //伪数据集合
        ArrayList<User> users = new ArrayList <>();
        User user1 = new User();
        user1.setId(1L);
        user1.setName("展示");
        user1.setAddress("陕西西安");
        users.add(user1);

        User user2 = new User();
        user2.setId(2L);
        user2.setName("李四");
        user2.setAddress("西安");
        users.add(user2);

        User user3 = new User();
        user3.setId(3L);
        user3.setName("王五");
        user3.setAddress("陕西西安");
        users.add(user3);


        ModelAndView modelAndView = new ModelAndView();
        //指定逻辑视图名
        modelAndView.setViewName("userList");

        //填充数据(返回数据)
        modelAndView.addObject("users", users);
        modelAndView.addObject("class", "tunlun23");

        return modelAndView;
    }

    @RequestMapping("/void")
    public void result(HttpServletRequest request, HttpServletResponse response) throws ServletException,
            IOException {
        //转发地址不变
        //request.getRequestDispatcher("/user/userlist").forward(request,response);

        //重定向地址改变
        response.sendRedirect("user/userlist");

        //response指定相应结果
        response.getWriter().write("hello...");
    }
}
